package dblayer;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import modellayer.ZipCode;

/**
 * The ZipcodeDB class to exchange data betwixt SQL database and java
 * @author Allan Eriksen, Andreas Rye, Casper Madsen, Christian Stidsborg, Stefan Bols
 */

public class ZipcodeDB {
	private Connection con;
	/**
	 * @param con
	 */
	
	
	/**
	 * Constructor for the ZipcodeDB, also creates a connection to the SQL Database
	 */
	public ZipcodeDB() {
		con = DBConnection.getInstance().getDBcon();
	}
	
	/**
	 * Search method using zipcode
	 * @param zipcode
	 * @return singleWhere(wClause)
	 */
	public ZipCode findZipcode(int zipcode) {
		String wClause = "zipcode="+zipcode;
		
		return singleWhere(wClause);
	}
	
	/**
	 * singleWhere method to execute a method in the database
	 * @param wClause
	 * @return zipcodeObj
	 */
	private ZipCode singleWhere(String wClause) {
		ResultSet results;
		ZipCode zipcodeObj = null;
		
		String query = buildQuery(wClause);
		
		try {
			Statement stmt = con.createStatement();
			stmt.setQueryTimeout(5);
			results = stmt.executeQuery(query);
			
			if ( results.next() )
			{
				zipcodeObj = buildZipcode(results);
			}
			else
			{
				zipcodeObj = null;
			}
			
			stmt.close();
		}
		catch (Exception ex) {
			System.out.println("SQL query: "+query);
			System.out.println("	error: "+ex);
		}
		
		return zipcodeObj;
	}

	/**
	 * A method which uses wClause parameters to construct a query, in a format that the SQL database understands
	 * @param wClause
	 * @return query
	 */
	private String buildQuery(String wClause) {
		String query = "SELECT zipcode, city FROM sem2_Zipcode";
		
		if ( ! wClause.isEmpty() )
		{
			query += " WHERE "+wClause;
		}
		
		return query;
	}

	/**
	 * A method which extracts data from the database into Java
	 * @param results
	 * @return zipcodeObj
	 */
	private ZipCode buildZipcode(ResultSet results) {
		ZipCode zipcodeObj = null;
		
		try {
			zipcodeObj = new ZipCode(results.getInt("zipcode"), results.getString("city"));
		}
		catch (SQLException e) {
			System.out.println("Error building Zipcode object!\nError: " + e);
		}
		
		return zipcodeObj;
	}
}